<?php
include_once '../../config.php';
include_once '../../lib/database.php';
include_once '../../functions.php';

if(isset($_GET['action']) && $_GET['action'] == 'Update'){
	$id = $_GET['id'];
	$action = 'update';
	$title = 'Edit Category';
	$button = 'Update';
	$sql = "SELECT id, name FROM category WHERE id='$id'";
	$row = $db->query($sql)->fetch_array();
	$name = $row['name'];
	include 'categories.form.html';
	exit();
}

if(isset($_GET['update'])){
	$id = $_POST['id'];
	$name = $_POST['name'];
	$sql = "UPDATE category SET name = '$name' WHERE id='$id'";
	$update = $db->query($sql);
	if(!$update){
		die("error" . mysql_error());
	}
	
	redirect('admin/categories');
	exit();
}

if(isset($_GET['add'])){
	$id ='';
	$name ='';
	$action ='add_category';
	$title = 'Add New Category';
	$button = 'Save';
	include 'categories.form.html';
	exit();
}

if(isset($_GET['add_category'])){
	$name = $_POST['name'];
	$sql = "INSERT INTO category (name) VALUES ('$name')";
	$insert = $db->query($sql);
	if(!$insert){
		die("error in adding new category" .  mysql_error());
	}
	redirect('admin/categories');
	exit();
}

if(isset($_GET['action']) && $_GET['action'] == 'Delete'){
	
	$id = $_GET['id'];
	$sql = "DELETE FROM jokecategory WHERE categoryid='$id'";
	$del = $db->query($sql);
	
	if(!$del){
		die("error in deleting from jokecategory" . mysql_error());
		exit();
	}
	
	$sql = "DELETE FROM category WHERE id='$id'";
	$del = $db->query($sql);
	
	if(!$del){
		die("error in deleting category" . mysql_error());
		exit();
	}
	
	redirect('admin/categories');
	exit();

}

$sql = "SELECT id, name FROM category ORDER BY id";
$result_set = $db->query($sql)->fetch_assoc();

if(!$result_set){
	die("error in displaying categories" . mysql_error());
}

include 'categories.php';

